<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
<head>
    <meta charset="UTF-8">
    <title>系统消息管理页面</title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
<!--    <link rel="stylesheet" href="/css/custom.form.css">-->
    <link rel="stylesheet" href="/js/zTree_v3/css/zTreeStyle/zTreeStyle.css">
    <style>
        .ztree li {
            line-height: 27px;
        }

        .ztree li span.button {
            width: 18px;
            height: 26px;
        }

        .ztree li span.button.ico_open {
            margin-top: 5px;
            margin-right: 0px;
        }

        .ztree li span.button.ico_docu {
            margin-top: 5px;
        }

        .ztree li a.curSelectedNode {
            height: 26px;
        }
    </style>
</head>
<body>
<div id="searchParam">
    <div class="layui-form-item" shiro:hasPermission="sys:message:list">
        <div class="layui-input-inline">
            <input type="text" id="msgContent" class="layui-input" autocomplete="off" placeholder="请输入消息内容">
        </div>
        <div class="layui-input-inline">
            <input type="text" id="msgTitle" class="layui-input" autocomplete="off" placeholder="请输入消息标题">
        </div>
        <div class="layui-input-inline" style="width: 300px;">
            <input type="text" class="layui-input" id="createTime" placeholder="请选择发送时间">
        </div>
        <div class="layui-input-inline ">
            <button class="layui-btn" id="search">
                查询
            </button>
            <button class="layui-btn" id="clearSearch">
                清空条件
            </button>
        </div>
    </div>

</div>
<div class="menu-table">
    <table class="layui-hide" id="log_table" lay-filter="log_table"></table>
    <div id="laypage" class="layui-laypage-btn"></div>
</div>
<!--发送系统消息DIV-->
<div class="panel panel-default operation_menu" id="sendMsgDiv" style="display:none;">
    <form class="layui-form layui-form-pane" action="" style="margin-top: 10px;margin-left: 10px;margin-right: 10px;" lay-filter="userEditFilter" autocomplete="off">
        <div class="layui-form-item">
            <label class="layui-form-label">标题</label>
            <div class="layui-input-block">
                <input type="text" name="msgTitle" id="msgTitleSend" lay-verify="required" placeholder="请输入标题" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">目标</label>
            <div class="layui-input-block">
                <select name="target" id="target" lay-filter="target" lay-verify="required">
                    <option value="" selected="">请选择目标</option>
                    <option value="1">平台</option>
                    <option value="2">北方社区</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">消息内容</label>
            <div class="layui-input-block">
                <textarea name="msgContent" id="msgContentSend" lay-verify="required" placeholder="请输入消息内容" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-form-label">消息接收者</div>
            <div class="layui-input-block">
                <ul id="treeMultiple" class="ztree" style="height: 330px; overflow-y: auto"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <div style="text-align: center;">
                <button class="layui-btn" id="sendMsgBtn">
                    发送消息
                </button>
            </div>
        </div>
    </form>
</div>
<!--广播消息DIV-->
<div class="panel panel-default operation_menu" id="broadcastDiv" style="display:none;">
    <div class="layui-form-item" style="margin-top: 15px;">
        <label class="layui-form-label">消息内容</label>
        <div class="layui-input-block">
            <textarea name="broadcastContent" id="broadcastContent" placeholder="请输入消息内容" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <div style="text-align: center;">
            <button class="layui-btn" id="sendBroadcastBtn">
                确定广播消息
            </button>
        </div>
    </div>
</div>
</body>
<script type="text/html" id="toolbar">
    <div class="layui-btn-group">
        <button type="button" class="layui-btn layui-btn-sm" lay-event="addObject" shiro:hasPermission="sys:message:add">
            <i class="layui-icon">&#xe608;</i> 新增消息
        </button>
    </div>
    <div class="layui-btn-group">
        <button shiro:hasPermission="sys:message:deleted" type="button" class="layui-btn layui-btn-sm" lay-event="getCheckData">
            <i class="layui-icon">&#xe640;</i> 批量删除
        </button>
    </div>
    <div class="layui-btn-group">
        <button shiro:hasPermission="sys:message:broadcast" type="button" class="layui-btn layui-btn-sm" lay-event="broadcast">
            <i class="layui-icon">&#xe641;</i> 发平台广播
        </button>
    </div>
</script>
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="sys:message:deleted">删除</a>
</script>
<script type="text/javascript" src="/layui/layui.all.js"></script>
<script type="text/javascript" src="/js/core.util.js"></script>
<script type="text/javascript" src="/js/zTree_v3/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="/js/zTree_v3/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="/js/zTree_v3/js/jquery.ztree.excheck.js"></script>
<script>
    let table = layui.table;
    let laypage = layui.laypage;
    let form = layui.form;
    let layer = layui.layer;
    let tree = layui.tree;
    let $2 = jQuery = layui.jquery;
    let laydate = layui.laydate;
    layui.use(['table', 'laypage', 'layer', 'laydate', 'tree'], function () {
        let searchParam = {
            msgContent: null,
            msgTitle: null,
            startTime: null,
            endTime: null,
            pageNum: 1,
            pageSize: 10
        };
        CoreUtil.sendAjax("/sys/message/list", JSON.stringify(searchParam), function (res) {
            //初始化分页器
            laypageTable(res.data.totalRows, searchParam.pageNum);
            //初始化渲染数据
            if (res.data.list != null) {
                loadTable(res.data.list);
            }
        }, "POST", false, function (res) {
            layer.msg("抱歉！您暂无获取列表的权限");
            let noAuthorityData = [];
            loadTable(noAuthorityData);
        });
        //渲染分页插件
        let laypageTable = function (count, currentPage) {
            laypage.render({
                elem: 'laypage'
                , count: count
                , limit: searchParam.pageSize
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                , curr: location.hash.replace('#!currentPage=', '') //获取起始页
                , hash: 'currentPage' //自定义hash值
                , limits: [10, 25, 50, 100, 300, 500, 2000]
                , jump: function (obj, first) {
                    if (!first) {
                        searchParam.pageNum = obj.curr;
                        searchParam.pageSize = obj.limit;
                        CoreUtil.sendAjax("/sys/message/list", JSON.stringify(searchParam), function (res) {
                            if (res.data.list != null) {
                                loadTable(res.data.list);
                                laypageTable(res.data.totalRows, searchParam.pageNum);
                            }
                        }, "POST", false, function (res) {
                            layer.msg("抱歉！您暂无获取列表的权限");
                            let noAuthorityData = [];
                            loadTable(noAuthorityData);
                        });
                    }
                }
            });
        };

        //渲染table
        let loadTable = function (data) {
            //展示已知数据
            table.render({
                elem: '#log_table'
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {type: 'xuhao', fixed: 'left', title: '序号', width: 50, type: 'numbers'},
                        {field: 'createUserName', title: '发送者', width: 120},
                        {field: 'receiveUserName', title: '接收者', width: 120},
                        {
                            field: 'readStatus', title: '状态', width: 100, templet: function (item) {
                                if (item.readStatus === 0) {
                                    return '<span class="layui-badge">未读</span>';
                                }
                                if (item.readStatus === 1) {
                                    return '<span class="layui-badge layui-bg-green">已读</span>';
                                }
                            }
                        },
                        {field: 'createTime', title: '发送时间', width: 220, sort: true},
                        {
                            field: 'target', title: '目标', width: 100, templet: function (item) {
                                if (item.target === '1') {
                                    return '平台';
                                }
                                if (item.target === '2') {
                                    return '北方社区';
                                }
                            }
                        },
                        {field: 'msgTitle', title: '消息标题', width: 270},
                        {field: 'msgContent', title: '消息内容', width: 700}
                    ]
                ]
                , data: data
                , even: true
                , limit: data.length
                , toolbar: '#toolbar'
            });
        };
        //日期范围
        laydate.render({
            elem: '#createTime'
            , type: 'datetime'
            , range: '~'
            , done: function (value, date, endDate) {
                if (value != null && value != undefined && value != "") {
                    searchParam.startTime = value.split("~")[0];
                    searchParam.endTime = value.split("~")[1];
                } else {
                    //清空时间的时候要清空以前选择的日期
                    searchParam.startTime = null;
                    searchParam.endTime = null;
                }
            }
        });
        //执行查询
        $2("#search").click(function () {
            searchParam.msgContent = $2("#msgContent").val();
            searchParam.msgTitle = $2("#msgTitle").val();
            searchParam.pageNum = 1;
            CoreUtil.sendAjax("/sys/message/list", JSON.stringify(searchParam), function (res) {
                //初始化分页器
                laypageTable(res.data.totalRows, searchParam.pageNum);
                //初始化渲染数据
                if (res.data.list != null) {
                    loadTable(res.data.list);
                }
            }, "POST", false, function (res) {
                layer.msg("抱歉！您暂无获取列表的权限");
                let noAuthorityData = [];
                loadTable(noAuthorityData);
            });
        });
        //清空查询条件
        $2("#clearSearch").click(function () {
            $2("#msgContent").val('');
            $2("#msgTitle").val('');
            $2("#createTime").val('');
        });

        //表头工具栏事件
        table.on('toolbar(log_table)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckData':
                    let data = checkStatus.data;
                    if (data.length == 0) {
                        layer.msg("请选择要批量删除的记录");
                    } else {
                        let logIds = [];
                        $2(data).each(function (index, item) {
                            logIds.push(item.id);
                        });
                        tipDialog(logIds);
                    }
                    break;
                case 'addObject':
                    layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        resize: false, //是否允许拉伸
                        maxmin: false, //最大最小化
                        title: "发送系统消息",
                        area: ['80%', '90%'],
                        content: $2("#sendMsgDiv") //引用的弹出层的页面层的方式加载修改界面表单
                    });
                    initTree();
                    break;
                case 'broadcast':
                    $2("#broadcastContent").val('');
                    layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        resize: false, //是否允许拉伸
                        maxmin: false, //最大最小化
                        title: "发送广播消息",
                        area: ['750px', '300px'],
                        content: $2("#broadcastDiv") //引用的弹出层的页面层的方式加载修改界面表单
                    });
                    break;
            }
        });

        let zTreeSetting = {
            view: {
                fontCss: {
                    color: "#203e82"
                }
            },
            callback: {  //点击文字，将节点设置为选中
                onClick: function (e, treeId, treeNode, clickFlag) {
                    let zTree = $.fn.zTree.getZTreeObj("treeMultiple");
                    zTree.checkNode(treeNode, !treeNode.checked, true);
                }
            },
            check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: {"Y": "s", "N": "ps"}
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id", //节点数据中保存唯一标识的属性名称
                    pIdKey: "pid", //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: 0 //根节点id
                }
            }
        };

        //初始化员工部门Tree
        let initTree = function () {
            CoreUtil.sendAjax("/sys/user/deptUserTree", null, function (res) {
                console.log(res.data);
                $.fn.zTree.init($("#treeMultiple"), zTreeSetting, res.data);
                // 获取树对象
                let treeObj = $.fn.zTree.getZTreeObj("treeMultiple");
                /* 获取所有树节点 */
                let nodes = treeObj.transformToArray(treeObj.getNodes());
                // 展开除第一级之外的其他节点
                for (let i = 0, length_1 = nodes.length; i < length_1; i++) {
                    if (nodes[i].level == 0) {
                        continue;
                    }
                    nodes[i].open = true;
                }
                //展开第一级节点
                treeObj.expandNode(nodes[0], true);
            }, "GET", false);
        };

        //删除前确认对话框
        let tipDialog = function (logIds) {
            layer.open({
                content: '确定要删除么',
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendAjax("/sys/message", JSON.stringify(logIds), function (res) {
                        layer.msg(res.msg);
                        $2(".layui-laypage-btn").click();
                    }, "DELETE", false, function (res) {
                        layer.msg("抱歉！您暂无此删除权限");
                    });
                }
            });
        };

        //获取指定字符串个数
        function getStrCount(scrstr, armstr) { //scrstr 源字符串 armstr 特殊字符
            let count = 0;
            while (scrstr.indexOf(armstr) != -1) {
                scrstr = scrstr.replace(armstr, "");
                count++;
            }
            return count;
        }

        //监听发送消息按钮
        $2(document).on('click', '#sendMsgBtn', function () {
            let receiveUserJsonParam = {
                msgContent: null,
                msgTitle: null,
                receiveUserJson: null,
                target: null,
            };
            let treeObj = $.fn.zTree.getZTreeObj("treeMultiple");
            let nodes = treeObj.getCheckedNodes(true);//获取选中节点值
            let receiveUserJsonTemp = "";
            for (let i = 0; i < nodes.length; i++) {
                if (nodes[i].type == 1) {
                    receiveUserJsonTemp = receiveUserJsonTemp + nodes[i].id + ",";
                }
            }
            receiveUserJsonParam.msgContent = $2("#msgContentSend").val();
            receiveUserJsonParam.msgTitle = $2("#msgTitleSend").val();
            if ($2("#msgContentSend").val() == null || $2("#msgContentSend").val() == '') {
                layer.msg("请输入标题！");
                return false;
            }
            if ($2("#msgTitleSend").val() == null || $2("#msgTitleSend").val() == '') {
                layer.msg("请输入消息内容！");
                return false;
            }
            if ($2("#target").val() == null || $2("#target").val() == '') {
                layer.msg("请选择目标！");
                return false;
            }
            let tempCount = getStrCount(receiveUserJsonTemp, ",");
            if (tempCount < 1) {
                layer.msg("请至少选择一个用户！");
                return false;
            }
            receiveUserJsonParam.receiveUserJson = receiveUserJsonTemp;
            receiveUserJsonParam.target = $2("#target").val();
            CoreUtil.sendAjax("/sys/message/add", JSON.stringify(receiveUserJsonParam), function (res) {
                // layer.msg(res.msg);
                layer.alert(res.msg, {icon: 2, title: '温馨提示',}, function (index) {
                    //关闭弹出层的回调操作
                    layer.close(index);
                    $2(".layui-laypage-btn").click();
                });
            }, "POST", false, function (res) {
                layer.msg("抱歉！您暂无此权限");
            });
        });

        //监听发送广播按钮
        $2(document).on('click', '#sendBroadcastBtn', function () {
            let broadcastContent = $2("#broadcastContent").val();
            if (broadcastContent == null || broadcastContent == '') {
                layer.msg("请输入消息内容！");
                return false;
            }
            CoreUtil.sendAjax("/sys/message/broadcast/" + broadcastContent, null, function (res) {
                layer.msg(res.msg);
                layer.closeAll(); //疯狂模式，关闭所有层
            }, "POST", false, function (res) {
                layer.msg("抱歉！您暂无此权限");
            });
        });
    });
</script>
</html>